package com.zprmb.udzt;

import android.content.Context;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.zprmb.udzt.activity.PayInvestActivity;
import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.ExplosionField;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.MyReceiver;
import com.zprmb.udzt.util.NumUtil;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.TimeUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.view.AddAndSubView;
import com.zprmb.udzt.view.AddAndSubView.OnNumChangeListener;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class V6DexterityPayInActivity extends BaseActivity implements VolleryUtil.OnButtonListener {
    private AddAndSubView addAndSubView;
    private TextView tv_v6_dexterity_pay_in_keyong;
    private TextView tv_v6_dexterity_pay_in_chiyou;
    private TextView tv_v6_dexterity_pay_in_shouyi;
    private Button tv_v6_dexterity_pay_in_updata;
    private Double million;
    private Double inAmount;
    private TextView tv_product_shouyi;
    private int remainAmount;
    private int increaseNum;// 增量
    private int minAmount;
    private String productId;
    private Double maxAmount;
    private TextView tv_min_increaseNum;
    private ImageView img_nowork;
    private Double availableAmount;
    private ListView lv_comment;
    private LinearLayout li_tishi;
    private TextView tv_tishi;
    private TextView check_mAgreement;
    private CheckBox check;
    private LinearLayout li_dexterity;
    private ExplosionField mExplosionField;//粉碎动画执行方法类
    private TextView tv_v6_dexterity_pay_in_daotime;
    private TextView tv_v6_dexterity_pay_in_shengyu;
    DecimalFormat df = new DecimalFormat("###0.00");
    private List<String> list = new ArrayList<String>();
    TextView tv_comment;
    private TextView tv_mAgreement;
    private WebView v4_webview;
    WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6exterity_payin_activity);
        setImmersionStatus();
        v4_webview = (WebView) findViewById(R.id.v4_webview);
        v4_webview.clearCache(true);

        v4_webview.setWebChromeClient(chromeClient);
        v4_webview.getSettings().setUseWideViewPort(true);

        v4_webview.getSettings().setLoadWithOverviewMode(true);
        v4_webview.getSettings().setSavePassword(true);
        v4_webview.getSettings().setSaveFormData(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        // enable navigator.geolocation
        v4_webview.getSettings().setGeolocationEnabled(true);
        v4_webview.getSettings().setGeolocationDatabasePath(
                "/data/data/org.itri.html5webview/databases/");
        // enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
        v4_webview.requestFocus();
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        // v4_webview.setScrollBarStyle(0);
        String ua = v4_webview.getSettings().getUserAgentString();
        v4_webview.getSettings().setUserAgentString(
                ua + "; " + "rmbbox_android");
        v4_webview.addJavascriptInterface(new JsInterfaces(this),
                "AndroidWebView");
        v4_webview.getSettings().setBuiltInZoomControls(true);
        v4_webview.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        v4_webview.getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);

        String appCachePath = getApplicationContext().getCacheDir()
                .getAbsolutePath();

        v4_webview.getSettings().setAllowFileAccess(true);
        v4_webview.getSettings().setAppCacheEnabled(true);
        v4_webview.getSettings().setJavaScriptEnabled(true);
        v4_webview.getSettings().setAppCachePath(appCachePath);
        v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
        v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
        String url = Constant.URL + "api/v3/claim/fund/intelliInto" + "?app=true&token=" + getURLToken();
        v4_webview.loadUrl(url);
        Log.d("3333333333333333333333", url);
        Log.d("3333333333333333333333", url);
        v4_webview.setWebViewClient(new WebViewClient() {

            @Override

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
//        Toast.makeText(this, "智投宝转入", Toast.LENGTH_SHORT).show();
//        setContentInview(this).setVisibility(View.INVISIBLE);
        setTitle("智投宝转入", V6DexterityPayInActivity.this);
        setgoback(V6DexterityPayInActivity.this);
//		IntentFilter mFilter = new IntentFilter();
//        mFilter.addAction("exit");       
//        this.registerReceiver(myReceiver,mFilter);
        check = (CheckBox) findViewById(R.id.check);
        tv_mAgreement = (TextView) findViewById(R.id.tv_mAgreement);
        check_mAgreement = (TextView) findViewById(R.id.check_mAgreement);
        li_dexterity = (LinearLayout) findViewById(R.id.li_dexterity);
        tv_comment = (TextView) findViewById(R.id.tv_comment);
        tv_v6_dexterity_pay_in_shengyu = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_shengyu);
        addAndSubView = (AddAndSubView) findViewById(R.id.add_subview);
//		lv_comment=(ListView)findViewById(R.id.lv_comment);
        tv_v6_dexterity_pay_in_keyong = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_keyong);
        tv_v6_dexterity_pay_in_chiyou = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_chiyou);
        tv_v6_dexterity_pay_in_shengyu = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_shengyu);
        tv_v6_dexterity_pay_in_updata = (Button) findViewById(R.id.tv_v6_dexterity_pay_in_updata);
        tv_v6_dexterity_pay_in_daotime = (TextView) findViewById(R.id.tv_v6_dexterity_pay_in_daotime);
        tv_product_shouyi = (TextView) findViewById(R.id.tv_product_shouyi);
        li_tishi = (LinearLayout) findViewById(R.id.li_tishi);
        tv_tishi = (TextView) findViewById(R.id.tv_tishi);
        img_nowork = (ImageView) findViewById(R.id.iv_v4_nonetwork);
        tv_min_increaseNum = (TextView) findViewById(R.id.tv_min_increaseNum);
        tv_product_shouyi.setVisibility(View.INVISIBLE);
        addAndSubView.setEditTextLayoutWidth(800);
        if (getScreenWidth() > 1080) {
            addAndSubView.setButtonLayoutParm(100, 100);
        } else {
            addAndSubView.setButtonLayoutParm(60, 60);
        }


        check.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    tv_v6_dexterity_pay_in_updata.setEnabled(true);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.v6button);
                } else {
                    tv_v6_dexterity_pay_in_updata.setEnabled(false);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.btn_unclick);
                }
            }
        });
        check_mAgreement.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (check.isChecked()) {
                    tv_v6_dexterity_pay_in_updata.setEnabled(false);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.btn_unclick);
                    check.setChecked(false);
                } else {
                    tv_v6_dexterity_pay_in_updata.setEnabled(true);
                    tv_v6_dexterity_pay_in_updata.setBackgroundResource(R.drawable.v6button);
                    check.setChecked(true);
                }
            }
        });
        tv_mAgreement.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent2 = new Intent(V6DexterityPayInActivity.this,
                        WebViewActivity.class);
                intent2.putExtra("url", "landing/currentAgreement?app=true&token=");


                intent2.putExtra("share", 1);
                intent2.putExtra("titleview", 1);
                intent2.putExtra("title", "《智投宝授权委托书》");
                startActivity(intent2);
            }
        });
        addAndSubView.setTextSize(20);
        addAndSubView.setButtonBgResource(R.drawable.jiahao, R.drawable.jianhao);
//		payIn();
        addAndSubView.setOnNumChangeListener(new OnNumChangeListener() {

            @Override
            public void onNumChange(View view, int num) {
                // TODO Auto-generated method stub
                changeComment();
            }
        });
        tv_v6_dexterity_pay_in_updata.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
//                verityUser();
            }
        });
    }

    MyReceiver myReceiver = new MyReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    private void payIn() {
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                LogUtils.e("转入", jsonObject.toString());

                if (jsonObject.optInt("success") == 1) {
//                    setContentInview(V6DexterityPayInActivity.this).setVisibility(View.VISIBLE);
                    img_nowork.setVisibility(View.GONE);
                    JSONObject json = jsonObject.optJSONObject("data");
                    tv_v6_dexterity_pay_in_keyong.setText(df.format(Double
                            .parseDouble(json.optString("userFundAvailableAmount")))
                    );
                    tv_v6_dexterity_pay_in_chiyou.setText(df.format(Double
                            .parseDouble(json.optString("currentAmount")))
                    );

                    remainAmount = json.optInt("maxAmount");
                    increaseNum = json.optInt("increaseNum");
                    minAmount = json.optInt("minAmount");
                    maxAmount = json.optDouble("holdCapAmount");
                    tv_v6_dexterity_pay_in_shengyu.setText(NumUtil.getQiantwo(json.optString("maxAmount")) + "元");
                    String time = TimeUtils.formatTime(new Date(Long
                            .valueOf(json.optString("nextWorkDay"))));
                    Log.e("时间", time);

                    tv_v6_dexterity_pay_in_daotime.setText("预期收益到账时间 :" + time);
                    productId = json.optString("productId");
                    inAmount = json.optDouble("maxTransferAmount");
                    availableAmount = json.optDouble("availableAmount");
                    tv_min_increaseNum.setText(minAmount + "元起投," + increaseNum + "元倍数递增");
//					addAndSubView.setMinnum(minAmount);
                    Gson gson = new Gson();
                    list = gson.fromJson(json.optString("promptList"),
                            new TypeToken<ArrayList<String>>() {
                            }.getType());
//							ArrayAdapter arrayAdapter = new ArrayAdapter(
//									V6DexterityPayInActivity.this, R.layout.text_item
//									);
//							arrayAdapter.addAll(list);
//							lv_comment.setAdapter(arrayAdapter);
                    String s = "";
                    for (int i = 0; i < list.size(); i++) {
                        s = s + list.get(i);
                    }
                    tv_comment.setText(s);
                    addAndSubView.setincreaseNum(increaseNum);
                    if (getIntent().getIntExtra("investamount", 0) != 0) {
//						addAndSubView.setNum(getIntent().getIntExtra("investamount", 0));
                        addAndSubView.setNum(100);
                    }


                } else {


                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6DexterityPayInActivity.this,
                                V6LoginActivity.class);
                        intent.putExtra("close", 1);
                        intent.putExtra("web", 1);
                        startActivity(intent);
                    } else {
                        ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
                                jsonObject.optString("comment"));
                    }

                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub
//                setContentInview(V6DexterityPayInActivity.this).setVisibility(View.INVISIBLE);
                img_nowork.setVisibility(View.VISIBLE);
                Toast.makeText(V6DexterityPayInActivity.this, "请求失败   请检查网络设置",
                        2000).show();
            }
        };
        vollery.setShow(true);
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("client", "android");
        vollery.setRequestMethod(1);
        vollery.execute(this, Constant.URL + "/api/v2/claim/fund/intelli/in", "");
    }

    @Override
    public void change() {

    }

    private class JsInterfaces {
        private Context mContext;

        public JsInterfaces(Context context) {
            this.mContext = context;
        }

        @JavascriptInterface
        public void appZTBIn(String amount) {
            Log.d("-----------------", "33333333333333333");
            Log.d("-----------------", "33333333333333333");
            Intent intent = new Intent(V6DexterityPayInActivity.this, PayInvestActivity.class);
            intent.putExtra("amount", "100");
            startActivity(intent);
//            finish();
            invest(amount);
        }

        public void invest(String amount) {

        }

        @JavascriptInterface
        public void showInfoFromJs(String name) {
        }

        @JavascriptInterface
        public String getToken() {
            return getToken();
        }

        @JavascriptInterface
        public void finishActivity() {

            V6DexterityPayInActivity.this.finish();
        }

        @JavascriptInterface
        public void toproduct(String[] list) {

        }


        @JavascriptInterface
        public void signout() {
//
        }

        @JavascriptInterface
        public void switchpage(String name) {

        }


    }

    private void invest(String amount) {
        AjaxParams params = new AjaxParams();
        amount = "100";
        params.put("amount", amount);
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                Log.e("转出", jsonObject.toString());
            }

            @Override
            public void onError() {

            }
        };
        vollery.OnButtonListener(this);
        vollery.setShow(true);
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("client", "android");
        vollery.setRequestMethod(1);
        vollery.execute(this, Constant.URL
                        + "api/v2/claim/fund/invest",
                params.toString());
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        payIn();
    }

    private void changeComment() {
        if (addAndSubView.getNum() > availableAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"请输入转入金额");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("账户可用余额不足");
            return;
        }
        if (addAndSubView.getNum() <= 0) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"请输入转入金额");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("请输入转入金额");
            return;
        }
        if (addAndSubView.getNum() < minAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额" + minAmount + "元起");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("转入金额" + minAmount + "元起");
            return;
        }

        if (addAndSubView.getNum() > inAmount
                && addAndSubView.getNum() <= remainAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额超出持有上限");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("转入金额超出持有上限");
            return;
        }
        if (addAndSubView.getNum() > maxAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额超出持有上限");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("输入金额超出持有上限" + Regular.getDecimalFormatZero(maxAmount / 10000) + "万元");
            return;
        }
        if (addAndSubView.getNum() > remainAmount) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"项目剩余金额不足");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("项目剩余金额不足");
            return;
        }
        if ((addAndSubView.getNum()
                - minAmount) % increaseNum != 0) {
//			ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
//					"转入金额的增量要为" + increaseNum + "的倍数");
            tv_min_increaseNum.setVisibility(View.GONE);
            li_tishi.setVisibility(View.VISIBLE);
            tv_tishi.setText("转入金额的增量要为" + increaseNum + "的倍数");
            return;
        }
        if ((addAndSubView.getNum()
                - minAmount) % increaseNum != 0 || addAndSubView.getNum() > remainAmount || addAndSubView.getNum() > inAmount
                && addAndSubView.getNum() < remainAmount || addAndSubView.getNum() < minAmount || addAndSubView.getNum() <= 0) {

        } else {
            tv_min_increaseNum.setVisibility(View.VISIBLE);
            li_tishi.setVisibility(View.GONE);
        }
    }

    private void verityUser() {
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                if (jsonObject.optInt("success") == 1) {
                    JSONObject json = jsonObject.optJSONObject("data");
                    Intent intent = null;

                    if (json.optString("bankMobileStatus") != null
                            && !json.optString("bankMobileStatus").equals("")
                            && json.optString("bankMobileStatus").equals(
                            "WAIT_CHECK")) {
                        intent = new Intent(V6DexterityPayInActivity.this,
                                BankCardActivity.class);
                        intent.putExtra("bankcard", json.optString("cardNo"));
                        intent.putExtra("isbank", 1);
                        intent.putExtra("logourl", json.optString("logoUrl"));
                        intent.putExtra("banknameEn",
                                json.optString("bankNameEn"));
                        intent.putExtra("banknameCn",
                                json.optString("bankNameCn"));
                        intent.putExtra("status",
                                json.optString("bankMobileStatus"));
                        startActivity(intent);
                        return;
                    }
                    if (!json.optBoolean("isBindCard")) {
                        intent = new Intent(V6DexterityPayInActivity.this,
                                V6WebviewChild.class);
                        intent.putExtra("url", Constant.URL + "h5/account/bankcard/bind/view?app=true&token=");
                        intent.putExtra("title", "智投宝");
                        startActivity(intent);
                        return;
                    }

                    intent = new Intent(V6DexterityPayInActivity.this,
                            PayDexterityActivity.class);
                    intent.putExtra("type", "IN");

                    tv_v6_dexterity_pay_in_updata
                            .setBackgroundResource(R.drawable.btn_unclick);
                    tv_v6_dexterity_pay_in_updata.setEnabled(false);
                    tv_v6_dexterity_pay_in_updata
                            .setBackgroundResource(R.drawable.v6button);
                    tv_v6_dexterity_pay_in_updata.setEnabled(true);
                    intent.putExtra("amount", addAndSubView.getNum() + "");
                    intent.putExtra("productId", productId);
                    LogUtils.e("智投宝id", productId);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_from_bottom,
                            R.anim.slide_out_to_bottom);
                } else {
                    if (jsonObject.optString("comment").equals("please login")) {
                        Intent intent = new Intent(V6DexterityPayInActivity.this,
                                V6LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToastUtil.showCenterToast(V6DexterityPayInActivity.this,
                                jsonObject.optString("comment"));
                    }
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("token", getToken());
        vollery.setHeaders("client", "android");
        vollery.setShow(true);
        vollery.setRequestMethod(0);
        vollery.execute(V6DexterityPayInActivity.this, Constant.URL
                + "/api/v5/user/userInfo", "");
    }

    private void setImmersionStatus() {
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
}
